﻿Imports Microsoft.Practices.Composite.Wpf.Regions
Imports Microsoft.Practices.Composite.Regions
Imports Infragistics.Windows.Ribbon
Imports System.Collections.Specialized
Imports System.ComponentModel

Namespace RegionAdapters

    Public Class ContextualTabGroupRegionAdapter
        Inherits RegionAdapterBase(Of ContextualTabGroup)

        Private m_regionTarget As ContextualTabGroup

        Protected Overrides Sub Adapt(ByVal region As Microsoft.Practices.Composite.Regions.IRegion, ByVal regionTarget As ContextualTabGroup)
            m_regionTarget = regionTarget

            'If control has child items, move them to the region and then bind control to region. Can't set ItemsSource if child items exist.

            ' Process an clear Tabs
            If regionTarget.Tabs.Count > 0 Then
                For Each childItem In regionTarget.Tabs
                    Dim rName As String = childItem.GetValue(RegionManager.RegionNameProperty)
                    If Not String.IsNullOrEmpty(rName) Then
                        region.RegionManager.AttachNewRegion(childItem, rName)
                    End If
                    region.Add(childItem)
                Next
                regionTarget.Tabs.Clear()
            End If

            AddHandler region.ActiveViews.CollectionChanged, AddressOf OnActiveViewsChanged

            ' Add Tabs
            For Each v In region.ActiveViews
                regionTarget.Tabs.Add(v)
            Next


        End Sub

        Private Sub OnActiveViewsChanged(ByVal sender As Object, ByVal e As NotifyCollectionChangedEventArgs)
            Select Case e.Action
                Case NotifyCollectionChangedAction.Add
                    For Each v In e.NewItems
                        m_regionTarget.Tabs.Add(v)
                    Next
                Case NotifyCollectionChangedAction.Remove
                    For Each v In e.OldItems
                        m_regionTarget.Tabs.Remove(v)
                    Next
            End Select
        End Sub

        Protected Overrides Function CreateRegion() As Microsoft.Practices.Composite.Regions.IRegion
            Return New AllActiveRegion
        End Function

    End Class

End Namespace